// index.js
import {
  post,
  get
} from '../../utils/request'
import {
  APIS
} from '../../utils/api';
import {timestampToTime} from '../../utils/util';
// 获取应用实例
const app = getApp()

Page({
  data: {
    payList: [],
    currentIndex: 1,
    currentTabIndex: 0,
    isShowStart: false,
    type: 'pay',
    tabs: ['充值', '消费'],
    currentShopName: '',
    currentShop: 1,
    payInfo: [],
    userInfo: {},
    orderList: [],
    isShowTip: false
  },
  onLoad() {
    const currentShopName = wx.getStorageSync('currentShopName');
    const currentShop = wx.getStorageSync('currentShop');
    const userInfo = wx.getStorageSync('userInfo');

    // 判断用户是否已登录
    if (!userInfo) {
      wx.navigateTo({
        url: '/subPackage/pages/login'
      })
      return;
    }
    this.setData({
      currentShopName,
      currentShop,
      userInfo
    });
    this.getRecharge();
    this.getUserInfo();
  },
  getPayInfo() {
    
    get(APIS.payInfo, { uid: this.data.userInfo.id }).then(res => {
      this.setData({
        payInfo: res.data
      });
    })
  },
  getOrderList() {
    get(APIS.order, {status: 0, uid: this.data.userInfo.id}).then(res => {
      this.setData({
        orderList: res.data.map(x => {
          return {
            ...x,
            end: x.end && x.end !== '-' ? timestampToTime(Number(x.end), 1) : '进行中',
          }
        })
      });
    })
  },
  getRecharge() {
    get(APIS.recharge, { shop: this.data.currentShop, used: 0, client: 'user'}).then(res => {
      const payList = res.data;
      const currentIndex = payList.findIndex(x => x.mainuse === 1);
      this.setData({
        payList,
        currentIndex
      })
    })
  },
  handleChange(e) {
    const {
      index
    } = e.currentTarget.dataset;
    this.setData({
      currentIndex: index
    });
  },
  handleTabChange(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      currentTabIndex: index
    });
    if (index === 0) {
      this.getPayInfo();
    }
    else {
      this.getOrderList();
    }
  },
  handlePay() {
    const { id } = this.data.payList[this.data.currentIndex];
    post(APIS.payOrder, {
      uid: this.data.userInfo.id,
      name: 'common',
      rid: id,
      shop: this.data.currentShop
    }).then(res => {
      const {wxpay} = res.data;
      console.log(res.data.payment_id)
      const that = this;
      wx.requestPayment({
        ...wxpay,
        success(rp) {
          that.getPayment(res.data.payment_id)
        },
        fail(res) {
          console.log('err', res);
        }
      });
    });
  },
  getPayment(id) {
    let times = 10;
    wx.showLoading({
      title: '充值中',
      mask: true
    });
    let interval = setInterval(async () => {
      let res = await get(`${APIS.payInfo}/${id}`);
      if (res.code === 0) {
        this.getUserInfo();
        clearInterval(interval);
        wx.hideLoading();
        this.setData({
          isShowStart: true,
        });
        wx.showToast({
          title: '充值成功',
          icon: 'none',
          mask: true,
          duration: 2000
        });
        this.setData({
          isShowTip: true
        });
        return;
      }
      if (times-- === 0) {
        clearInterval(interval);
        wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: "充值延迟，请稍后查询"
        })
      }
    }, 3000)
  },
  getUserInfo() {
    let userInfo = this.data.userInfo;
    get(`${APIS.user}/${userInfo.id}`).then(res => {
      wx.setStorageSync('userInfo', res.data);
      this.setData({
        userInfo: res.data
      })
    })
  },
  handleJumpShop() {
    wx.switchTab({
      url: '/pages/shop/index'
    })
  },
  handleClose() {
    this.setData({
      isShowTip: false
    });
  },
  handleDetail() {
    const type = this.data.type;
    this.setData({
      type: type === 'pay' ? 'detail' : 'pay'
    });
    if (type === 'pay') {
      this.getPayInfo();
    }
  },
  onShareAppMessage() {
    return getApp().globalData.shareMessage
  }
})